﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HR.ProjectX.BLL.Services.CustomerService;
using HR.ProjectX.GUI.ViewModels.Customer;
using HR.ProjectX.BLL.Messaging;

namespace HR.ProjectX.GUI.Controllers
{
    public class CustomerController : Controller
    {
        private readonly ICustomerService _customerService;

        public CustomerController(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Register()
        {
            CustomerRegisterView customerView = InitializeCustomerRegisterViewWithIssue(false, "");

            return View(customerView);
        }

        [HttpPost]
        public ActionResult Register(CustomerRegisterView customerView)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    CreateCustomerRequest request = new CreateCustomerRequest();
                    request.Name = customerView.Name;
                    request.Gender = customerView.Gender;
                    request.Email = customerView.Email;
                    request.PhoneNumber = customerView.PhoneNumber;
                    request.Address = customerView.Address;
                    request.Town = customerView.Town;
                    request.Country = customerView.Country;

                    _customerService.CreateCustomer(request);

                    TempData["Success"] = "True";

                    return RedirectToAction("ConfirmRegistration");
                }
                catch (Exception e)
                {
                    CustomerRegisterView errorView = InitializeCustomerRegisterViewWithIssue(true, e.Message);

                    return View(errorView);
                }
            }

            return View(customerView);
        }

        public ActionResult ConfirmRegistration()
        {
            if (TempData["Success"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        private CustomerRegisterView InitializeCustomerRegisterViewWithIssue(bool hasIssue, string message)
        {
            CustomerRegisterView customerView = new CustomerRegisterView();
            customerView.HasIssue = hasIssue;
            customerView.Message = message;

            return customerView;
        }

    }
}
